import { PrismaClient } from '@prisma/client';
import { deepSeekAPI } from '../utils/DeepSeekAPI';

const prisma = new PrismaClient();

// AI分析结果接口
export interface StockAIAnalysisResult {
  overallScore: number;
  investmentAdvice: string;
  riskLevel: string;
  technicalAnalysis: string;
  fundamentalAnalysis: string;
  marketSentiment: string;
  keyFactors: string[];
  targetPriceRange: string;
  confidenceLevel: number;
}

// 大分类AI分析结果接口
export interface CategoryAIAnalysisResult {
  marketScore: number;
  trendDirection: string;
  investmentStrategy: string;
  hotSectors: string[];
  riskWarnings: string[];
  opportunities: string[];
  technicalIndicators: string;
  capitalFlow: string;
}

/**
 * AI智能分析服务
 * 提供股票个股和大分类的AI分析功能
 */
export class AIAnalysisService {
  
  /**
   * 获取股票的AI分析结果
   * @param stockId 股票ID
   * @param forceRefresh 是否强制刷新分析结果
   * @returns AI分析结果
   */
  async getStockAIAnalysis(stockId: number, forceRefresh: boolean = false): Promise<StockAIAnalysisResult | null> {
    try {
      // 使用标准化的日期格式避免时区和精度问题
      const todayStr = new Date().toISOString().split('T')[0];
      const today = new Date(todayStr + 'T00:00:00.000Z');

      // 检查是否存在今日的分析结果
      if (!forceRefresh) {
        const existingAnalysis = await prisma.stockAIAnalysis.findFirst({
          where: {
            stockId,
            analysisDate: today,
          },
        });

        if (existingAnalysis) {
          return this.formatStockAnalysisResult(existingAnalysis);
        }
      }

      // 获取股票详细数据
      const stockData = await this.getStockDetailData(stockId);
      if (!stockData) {
        throw new Error(`未找到股票ID为 ${stockId} 的数据`);
      }

      // 调用AI进行分析
      const aiResponse = await deepSeekAPI.analyzeStock(stockData, 'individual');
      const analysisResult = this.parseAIResponse(aiResponse);

      // 保存或更新分析结果到数据库 (使用 upsert 避免唯一约束冲突)
      const savedAnalysis = await prisma.stockAIAnalysis.upsert({
        where: {
          stockId_analysisDate: {
            stockId: stockId,
            analysisDate: today,
          },
        },
        update: {
          overallScore: analysisResult.overallScore,
          investmentAdvice: analysisResult.investmentAdvice,
          riskLevel: analysisResult.riskLevel,
          technicalAnalysis: analysisResult.technicalAnalysis,
          fundamentalAnalysis: analysisResult.fundamentalAnalysis,
          marketSentiment: analysisResult.marketSentiment,
          keyFactors: analysisResult.keyFactors,
          targetPriceRange: analysisResult.targetPriceRange,
          confidenceLevel: analysisResult.confidenceLevel,
          updatedAt: new Date(),
        },
        create: {
          stockId,
          overallScore: analysisResult.overallScore,
          investmentAdvice: analysisResult.investmentAdvice,
          riskLevel: analysisResult.riskLevel,
          technicalAnalysis: analysisResult.technicalAnalysis,
          fundamentalAnalysis: analysisResult.fundamentalAnalysis,
          marketSentiment: analysisResult.marketSentiment,
          keyFactors: analysisResult.keyFactors,
          targetPriceRange: analysisResult.targetPriceRange,
          confidenceLevel: analysisResult.confidenceLevel,
          analysisDate: today,
        },
      });

      return this.formatStockAnalysisResult(savedAnalysis);
    } catch (error) {
      console.error('获取股票AI分析失败:', error);
      throw new Error(`股票AI分析失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  /**
   * 获取大分类的AI分析结果
   * @param categoryKey 大分类键值
   * @param forceRefresh 是否强制刷新分析结果
   * @returns AI分析结果
   */
  async getCategoryAIAnalysis(categoryKey: string, forceRefresh: boolean = false): Promise<CategoryAIAnalysisResult | null> {
    try {
      // 使用标准化的日期格式避免时区和精度问题
      const todayStr = new Date().toISOString().split('T')[0];
      const today = new Date(todayStr + 'T00:00:00.000Z');

      // 检查是否存在今日的分析结果
      if (!forceRefresh) {
        const existingAnalysis = await prisma.categoryAIAnalysis.findFirst({
          where: {
            categoryKey,
            analysisDate: today,
          },
        });

        if (existingAnalysis) {
          return this.formatCategoryAnalysisResult(existingAnalysis);
        }
      }

      // 获取大分类市场数据
      const categoryData = await this.getCategoryMarketData(categoryKey);
      if (!categoryData) {
        throw new Error(`未找到大分类 ${categoryKey} 的市场数据`);
      }

      // 调用AI进行分析
      const aiResponse = await deepSeekAPI.analyzeStock(categoryData, 'category');
      const analysisResult = this.parseCategoryAIResponse(aiResponse);

      // 保存或更新分析结果到数据库 (使用 upsert 避免唯一约束冲突)
      const savedAnalysis = await prisma.categoryAIAnalysis.upsert({
        where: {
          categoryKey_analysisDate: {
            categoryKey: categoryKey,
            analysisDate: today,
          },
        },
        update: {
          categoryName: categoryData.categoryName,
          marketScore: analysisResult.marketScore,
          trendDirection: analysisResult.trendDirection,
          investmentStrategy: analysisResult.investmentStrategy,
          hotSectors: analysisResult.hotSectors,
          riskWarnings: analysisResult.riskWarnings,
          opportunities: analysisResult.opportunities,
          technicalIndicators: analysisResult.technicalIndicators,
          capitalFlow: analysisResult.capitalFlow,
          updatedAt: new Date(),
        },
        create: {
          categoryKey,
          categoryName: categoryData.categoryName,
          marketScore: analysisResult.marketScore,
          trendDirection: analysisResult.trendDirection,
          investmentStrategy: analysisResult.investmentStrategy,
          hotSectors: analysisResult.hotSectors,
          riskWarnings: analysisResult.riskWarnings,
          opportunities: analysisResult.opportunities,
          technicalIndicators: analysisResult.technicalIndicators,
          capitalFlow: analysisResult.capitalFlow,
          analysisDate: today,
        },
      });

      return this.formatCategoryAnalysisResult(savedAnalysis);
    } catch (error) {
      console.error('获取大分类AI分析失败:', error);
      throw new Error(`大分类AI分析失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  /**
   * 批量刷新股票AI分析
   * @param stockIds 股票ID数组
   * @returns 成功和失败的统计
   */
  async batchRefreshStockAnalysis(stockIds: number[]): Promise<{ success: number; failed: number }> {
    let success = 0;
    let failed = 0;

    for (const stockId of stockIds) {
      try {
        await this.getStockAIAnalysis(stockId, true);
        success++;
      } catch (error) {
        console.error(`股票ID ${stockId} 分析失败:`, error);
        failed++;
      }
      
      // 添加延迟避免API限流
      await this.sleep(1000);
    }

    return { success, failed };
  }

  /**
   * 批量刷新大分类AI分析
   * @param categoryKeys 大分类键值数组
   * @returns 成功和失败的统计
   */
  async batchRefreshCategoryAnalysis(categoryKeys: string[]): Promise<{ success: number; failed: number }> {
    let success = 0;
    let failed = 0;

    for (const categoryKey of categoryKeys) {
      try {
        await this.getCategoryAIAnalysis(categoryKey, true);
        success++;
      } catch (error) {
        console.error(`大分类 ${categoryKey} 分析失败:`, error);
        failed++;
      }
      
      // 添加延迟避免API限流
      await this.sleep(2000);
    }

    return { success, failed };
  }

  /**
   * 获取股票详细数据
   */
  private async getStockDetailData(stockId: number) {
    return await prisma.stock.findUnique({
      where: { id: stockId },
      include: {
        market: true,
        realtime: true,
        ratings: {
          orderBy: { ratingDate: 'desc' },
          take: 1,
        },
        dailyData: {
          orderBy: { tradeDate: 'desc' },
          take: 30, // 获取最近30天的历史数据
        },
      },
    });
  }

  /**
   * 获取大分类市场数据
   */
  private async getCategoryMarketData(categoryKey: string) {
    // 大分类映射
    const categoryMap: Record<string, { name: string; markets: string[] }> = {
      a_stock: { name: 'A股市场', markets: ['SH', 'SZ', 'NEEQ'] },
      hk_stock: { name: '香港市场', markets: ['HK'] },
      us_stock: { name: '美股市场', markets: ['US'] },
      uk_stock: { name: '英股市场', markets: ['UK'] },
    };

    const category = categoryMap[categoryKey];
    if (!category) {
      return null;
    }

    // 获取该分类下的股票统计数据
    const totalStocks = await prisma.stock.count({
      where: {
        market: {
          marketCode: { in: category.markets },
        },
        status: 1,
      },
    });

    // 获取实时数据统计
    const priceChanges = await prisma.stockRealtime.findMany({
      where: {
        stock: {
          market: {
            marketCode: { in: category.markets },
          },
          status: 1,
        },
      },
      select: {
        changePercent: true,
        turnover: true,
        volume: true,
      },
    });

    // 计算统计数据
    const riseCount = priceChanges.filter(p => p.changePercent && Number(p.changePercent) > 0).length;
    const fallCount = priceChanges.filter(p => p.changePercent && Number(p.changePercent) < 0).length;
    const flatCount = priceChanges.filter(p => p.changePercent && Number(p.changePercent) === 0).length;
    
    const limitUpCount = priceChanges.filter(p => p.changePercent && Number(p.changePercent) >= 9.8).length;
    const limitDownCount = priceChanges.filter(p => p.changePercent && Number(p.changePercent) <= -9.8).length;
    const bigRiseCount = priceChanges.filter(p => p.changePercent && Number(p.changePercent) >= 5).length;
    const bigFallCount = priceChanges.filter(p => p.changePercent && Number(p.changePercent) <= -5).length;

    const avgChangePercent = priceChanges.length > 0
      ? priceChanges.reduce((sum, p) => sum + (Number(p.changePercent) || 0), 0) / priceChanges.length
      : 0;

    const totalTurnover = priceChanges.reduce((sum, p) => sum + (Number(p.turnover) || 0), 0);
    const activeStocks = priceChanges.filter(p => p.volume && p.volume > 0).length;

    return {
      categoryKey,
      categoryName: category.name,
      totalStocks,
      riseCount,
      fallCount,
      flatCount,
      limitUpCount,
      limitDownCount,
      bigRiseCount,
      bigFallCount,
      avgChangePercent,
      totalTurnover,
      activeStocks,
    };
  }

  /**
   * 解析个股AI分析响应
   */
  private parseAIResponse(aiResponse: string): StockAIAnalysisResult {
    try {
      // 尝试从响应中提取JSON
      const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
      if (!jsonMatch) {
        throw new Error('AI响应中未找到有效的JSON格式');
      }

      const parsed = JSON.parse(jsonMatch[0]);
      
      return {
        overallScore: Math.max(1, Math.min(10, parseInt(parsed.overallScore) || 5)),
        investmentAdvice: parsed.investmentAdvice || '暂无投资建议',
        riskLevel: parsed.riskLevel || '中等风险',
        technicalAnalysis: parsed.technicalAnalysis || '暂无技术分析',
        fundamentalAnalysis: parsed.fundamentalAnalysis || '暂无基本面分析',
        marketSentiment: parsed.marketSentiment || '暂无市场情绪分析',
        keyFactors: Array.isArray(parsed.keyFactors) ? parsed.keyFactors : ['暂无关键因素'],
        targetPriceRange: parsed.targetPriceRange || '暂无目标价位',
        confidenceLevel: Math.max(1, Math.min(10, parseInt(parsed.confidenceLevel) || 5)),
      };
    } catch (error) {
      console.error('解析AI响应失败:', error);
      // 返回默认值
      return {
        overallScore: 5,
        investmentAdvice: 'AI分析解析失败，请稍后重试',
        riskLevel: '中等风险',
        technicalAnalysis: '技术分析数据解析失败',
        fundamentalAnalysis: '基本面分析数据解析失败',
        marketSentiment: '市场情绪分析数据解析失败',
        keyFactors: ['数据解析异常'],
        targetPriceRange: '暂无目标价位',
        confidenceLevel: 3,
      };
    }
  }

  /**
   * 解析大分类AI分析响应
   */
  private parseCategoryAIResponse(aiResponse: string): CategoryAIAnalysisResult {
    try {
      const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
      if (!jsonMatch) {
        throw new Error('AI响应中未找到有效的JSON格式');
      }

      const parsed = JSON.parse(jsonMatch[0]);
      
      return {
        marketScore: Math.max(1, Math.min(10, parseInt(parsed.marketScore) || 5)),
        trendDirection: parsed.trendDirection || '震荡',
        investmentStrategy: parsed.investmentStrategy || '暂无投资策略',
        hotSectors: Array.isArray(parsed.hotSectors) ? parsed.hotSectors : ['暂无热点板块'],
        riskWarnings: Array.isArray(parsed.riskWarnings) ? parsed.riskWarnings : ['暂无风险提示'],
        opportunities: Array.isArray(parsed.opportunities) ? parsed.opportunities : ['暂无投资机会'],
        technicalIndicators: parsed.technicalIndicators || '暂无技术指标分析',
        capitalFlow: parsed.capitalFlow || '暂无资金流向分析',
      };
    } catch (error) {
      console.error('解析大分类AI响应失败:', error);
      return {
        marketScore: 5,
        trendDirection: '震荡',
        investmentStrategy: 'AI分析解析失败，请稍后重试',
        hotSectors: ['数据解析异常'],
        riskWarnings: ['数据解析异常'],
        opportunities: ['数据解析异常'],
        technicalIndicators: '技术指标分析数据解析失败',
        capitalFlow: '资金流向分析数据解析失败',
      };
    }
  }

  /**
   * 格式化股票分析结果
   */
  private formatStockAnalysisResult(analysis: any): StockAIAnalysisResult {
    return {
      overallScore: analysis.overallScore,
      investmentAdvice: analysis.investmentAdvice,
      riskLevel: analysis.riskLevel,
      technicalAnalysis: analysis.technicalAnalysis,
      fundamentalAnalysis: analysis.fundamentalAnalysis,
      marketSentiment: analysis.marketSentiment,
      keyFactors: analysis.keyFactors,
      targetPriceRange: analysis.targetPriceRange,
      confidenceLevel: analysis.confidenceLevel,
    };
  }

  /**
   * 格式化大分类分析结果
   */
  private formatCategoryAnalysisResult(analysis: any): CategoryAIAnalysisResult {
    return {
      marketScore: analysis.marketScore,
      trendDirection: analysis.trendDirection,
      investmentStrategy: analysis.investmentStrategy,
      hotSectors: analysis.hotSectors,
      riskWarnings: analysis.riskWarnings,
      opportunities: analysis.opportunities,
      technicalIndicators: analysis.technicalIndicators,
      capitalFlow: analysis.capitalFlow,
    };
  }

  /**
   * 休眠函数
   */
  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// 单例模式导出
export const aiAnalysisService = new AIAnalysisService();